#!/bin/bash
# EOS automount check for Nagios
# Version 0.1, last modified: 11.12.2018
# Bugs and comments to Haibo Li && Yujiang Bi (lihaibo@ihep.ac.cn, biyujiang@ihep.ac.cn)

#
# ChangeLog
# 0.1 - 11.12.2018:
#    - return immediately if transport endpoint is not connected
# 0.2 - 17.05.2019:
#    - if "transport endpoint is not connected", then exec "umount -l /eos/daocheng"
#    - start of ChangeLog
# 0.3 - 07.04.2020
#    - fix the bug that when a job is accessing /eos/daocheng, the command "umount -l /eos/daocheng" cannot stop the eosd process
#    - add the "killall eosd" after "umount -l"

VERSION=0.1

STATUS_OK=0
STATUS_WARNING=1     # Check timed out or EOS resource consumption high or
                     # previous error status detected
STATUS_CRITICAL=2    # EOS not working
STATUS_UNKNOWN=3     # Internal or usage error

RETURN_STATUS=$STATUS_OK
TIMEOUT_SECONDS=120

EOS_MOUNT_DIR="/eos/daocheng"
SUBDIR="mirror"

usage() {
   /bin/echo "Usage:   $0 "
   /bin/echo "Example: $0 "
   /bin/echo "Options:"
   /bin/echo "  -t  second after which the check times out with a warning (default: ${TIMEOUT_SECONDS})"
   /bin/echo "  -n  run extended network checks"
   /bin/echo "  -m  check memory consumption of the cvmfs2 process"
   /bin/echo "      (less than 50M or 1% of available memory)"
}

version() {
   /bin/echo "EOS automount check for Nagios, version: $VERSION"
}



function send_mail(){
	echo "Warning"|mail -s "$(hostname -s) eos automount $1" -c biyujiang@ihep.ac.cn  lihaibo@ihep.ac.cn >> /dev/null 2&1
}

# Grab mountpoint / basic availability
cd "${EOS_MOUNT_DIR}/$SUBDIR" && ls . > /dev/null
if [ $? -ne 0 ]; then
	/bin/echo "SERVICE STATUS: failed to access ${EOS_MOUNT_DIR}/$SUBDIR"
	umount -l ${EOS_MOUNT_DIR}
	killall eosd
	send_mail "SERVICE STATUS: failed to access ${EOS_MOUNT_DIR}/$SUBDIR"
	exit $STATUS_CRITICAL
fi

echo "SERVICE STATUS: OK"
exit $RETURN_STATUS


#currentid=$(echo $$)
#oldpid=$(ps -ef|grep check_eos_mount|grep -v grep | grep -v $currentid |awk '{print $2}')

#if [ "t$oldpid" != "t" ];then
#	send_mail "critical: check_eos_mount script lock" "Please recover it manually"
#        exit $WARN
#fi

